package com.dankegongyu.lib.common.widget.imageview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import androidx.appcompat.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.dankegongyu.lib.common.R;

/**
 * 高度确定的情况下，保持原图比例，宽针对高适配
 *
 * Demo:
 * <pre>
 * <com.dankegongyu.lib.common.widget.imageview.ScaledWidthImageView
 *      android:layout_width="wrap_content"
 *      android:layout_height="50dp"
 *      app:original_width = "50"
 *      app:original_height = "50"
 *      android:scaleType="fitXY"
 *      android:src="@drawable/ic_launcher" />
 * </pre>
 *
 * @author wpq
 * @version 1.0
 */
public class ScaledWidthImageView extends AppCompatImageView {

    private int originalWidth, originalHeight;

    public ScaledWidthImageView(Context context) {
        super(context);
        setScaleType(ScaleType.FIT_XY);
    }

    public ScaledWidthImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setScaleType(ScaleType.FIT_XY);

        @SuppressLint("CustomViewStyleable")
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ScaledImageView);
        try {
            originalWidth = ta.getInteger(R.styleable.ScaledImageView_original_width, 0);
            originalHeight = ta.getInteger(R.styleable.ScaledImageView_original_height, 0);
        } finally {
            ta.recycle();
        }
    }

    /**
     * 原图尺寸（px）
     *
     * @param originalWidth  原图宽（px）
     * @param originalHeight 原图高（px）
     */
    public void setOriginalSize(int originalWidth, int originalHeight) {
        this.originalWidth = originalWidth;
        this.originalHeight = originalHeight;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (originalWidth > 0 && originalHeight > 0) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            float scale = (float) originalWidth / (float) originalHeight;
            if (height > 0) {
                width = (int) (height * scale);
            }
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
